import { reactive, ref } from 'vue'
import { DeptModel, SelectNode } from '@/api/dept/DeptModel'
import { getDeptParentApi } from '@/api/dept/dept'
import { ElTree } from 'element-plus'

export default function useParent(emit: any) {
  // 这个是原始的写法，下面是简单的写法，也可以起效果
  // const parentTree = ref<InstanceType<typeof ElTree>>()
  const parentTree = ref()
  const treeData = reactive({
    data: []
  })
  const defaultProps = reactive({
    children: 'children', //设置树的children
    label: 'name' //设置树的名字属性字段
  })
  const selectNode = reactive<SelectNode>({
    id: '',
    name: ''
  })
  const handleNodeClick = (data: DeptModel) => {
    console.log(data)
    console.log(data.name)
    selectNode.id = data.id
    selectNode.name = data.name
    emit('select', selectNode)
  }
  const openBtn = data => {
    // console.log(data,parentTree)
    data.open = !data.open
    parentTree.value.store.nodesMap[data.id].expanded = !data.open
    // 老的写法需要对应使用判断的功能
    // if (parentTree.value) {
    // parentTree.value.store.nodesMap[data.id].expanded = !data.open
    // }
  }

  // 获取树的数据
  const getTreeData = async () => {
    let res = await getDeptParentApi()
    if (res && res.code === 200) {
      treeData.data = res.data
    }
  }

  return {
    treeData,
    defaultProps,
    handleNodeClick,
    getTreeData,
    selectNode,
    openBtn,
    parentTree
  }
}
